const https = require('https');
const fs = require('fs').promises;
const path = require('path');
const crypto = require('crypto');
const { promisify } = require('util');
const stream = require('stream');

const pipeline = promisify(stream.pipeline);

const IMAGE_DIR = path.join(__dirname, '../../../images');

// 确保图片目录存在
async function ensureImageDir() {
  try {
    await fs.access(IMAGE_DIR);
  } catch (error) {
    await fs.mkdir(IMAGE_DIR, { recursive: true });
  }
}

async function downloadImage(url) {
  if (!url) return null;
  
  await ensureImageDir();
  
  const hash = crypto.createHash('sha256').update(url).digest('hex');
  const ext = path.extname(url).split('?')[0] || '.jpg';
  const fileName = `${hash}${ext}`;
  const filePath = path.join(IMAGE_DIR, fileName);
  
  try {
    // 检查文件是否已存在
    await fs.access(filePath);
    return fileName;
  } catch (error) {
    // 文件不存在，下载它
    return new Promise((resolve, reject) => {
      https.get(url, async (response) => {
        if (response.statusCode !== 200) {
          reject(new Error(`下载图片失败，状态码: ${response.statusCode}`));
          return;
        }
        
        try {
          await pipeline(response, fs.createWriteStream(filePath));
          resolve(fileName);
        } catch (error) {
          reject(error);
        }
      }).on('error', reject);
    });
  }
}

module.exports = {
  downloadImage
};  